class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def maximumAverageSubtree(self, root):
        """
        :type root: TreeNode
        :rtype: float
        """
        self.avg = 0

        def search(node):
            if not node:
                return 0, 0
            else:
                left_sum, left_count = search(node.left)
                right_sum, right_count = search(node.right)
                now_sum = node.val + left_sum + right_sum
                now_count = left_count + 1 + right_count
                self.avg = max(self.avg, now_sum / now_count)
                return now_sum, now_count

        search(root)
        return self.avg